import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'environment.dart';

class AppConfig {
  static late Environment _environment;
  static Environment get environment => _environment;

  // 配置项
  static String get appName => dotenv.env['APP_NAME'] ?? 'Flutter App';
  static String get apiBaseUrl => dotenv.env['API_BASE_URL'] ?? '';
  static String get apiKey => dotenv.env['API_KEY'] ?? '';
  static String get databaseUrl => dotenv.env['DATABASE_URL'] ?? '';
  static bool get debugMode => dotenv.env['DEBUG_MODE']?.toLowerCase() == 'true';
  static String get logLevel => dotenv.env['LOG_LEVEL'] ?? 'info';
  static String get version => dotenv.env['VERSION'] ?? '1.0.0';

  // 初始化配置
  static Future<void> initialize({String? envName}) async {
    // 确定环境
    _environment = Environment.fromString(envName);
    
    // 根据环境加载对应的.env文件
    String envFile = _getEnvFileName(_environment);

    print("envFile ---> : $envFile");

    try {
      await dotenv.load(fileName: envFile);
      print('✅ 成功加载环境配置: $envFile');
      print('📱 应用名称: ${AppConfig.appName}');
      print('🌐 API地址: ${AppConfig.apiBaseUrl}');
      print('🔧 调试模式: ${AppConfig.debugMode}');
      print('📝 日志级别: ${AppConfig.logLevel}');
    } catch (e) {
      print('❌ 加载环境配置失败: $e');
      // 尝试加载默认配置
      try {
        await dotenv.load(fileName: '.env');
        print('✅ 已加载默认环境配置');
      } catch (defaultError) {
        print('❌ 加载默认环境配置也失败: $defaultError');
        rethrow;
      }
    }
  }

  // 获取环境文件名
  static String _getEnvFileName(Environment env) {
    switch (env) {
      case Environment.dev:
        return '.env.dev';
      case Environment.test:
        return '.env.test';
      case Environment.prod:
        return '.env.prod';
    }
  }

  // 获取当前环境信息
  static Map<String, dynamic> getEnvironmentInfo() {
    return {
      'environment': _environment.value,
      'appName': appName,
      'apiBaseUrl': apiBaseUrl,
      'debugMode': debugMode,
      'logLevel': logLevel,
      'version': version,
    };
  }

  // 检查是否为生产环境
  static bool get isProduction => _environment == Environment.prod;
  
  // 检查是否为开发环境
  static bool get isDevelopment => _environment == Environment.dev;
  
  // 检查是否为测试环境
  static bool get isTesting => _environment == Environment.test;
}
